import jwt
import datetime

# token 功能类

# 设置key
key = '1234'


class JWTTool:
    # 需要传递自己要添加的信息 比如过期时间 用户id
    # 参数 user 值得是用户id
    def gettoken(self, user):
        # 过期时间设置
        exp = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
        # 设置载荷信息
        payload = {
            "user": user,
            "exp": exp
        }
        # 生成token
        token = jwt.encode(payload, key, algorithm='HS256')
        # 浏览器需要我们添加一个 标识头
        return "Bearer " + token

    # 解析token
    def parsejwt(self, token):
        tokendata = token.split(" ")[1]
        try:
            payload = jwt.decode(tokendata, key, algorithms=['HS256'])
        except:
            payload = None
        return payload


tool = JWTTool()  # 类的实例
token = tool.gettoken(1)  # 生成token
payload = tool.parsejwt(token)  # 解析token
print(payload)
